﻿namespace ChinaUnicom.Tasks
{
    using System;
    using System.Linq;
    using ChinaUnicom.Models;
    using Avatar.Schedule;
    using Avatar;
    using System.Net;

    public class PointTask : ITask
    {
        const string PointName = "累计积分";

        public Point Point { get; private set; }

        public PointTask()
        {
            Point = new Point();
            Point.Occurred = DateTime.Now;
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.RequestPoint(x =>
            {
                try
                {
                    if (x.Status == WebExceptionStatus.Success)
                    {
                        /*查询日期：2012年11月17日 
                            【积分信息如下】 
                            当前可用积分： 618 
                            已兑换积分： 0 
                            上月产生积分： 0 
                            累计积分： 618*/

                        Point.Items = Factory.Parser.Parse(x.Result, ItemType.Point);

                        var point = Point.Items.SingleOrDefault(f => f.Name.IgnoreCaseEquals(PointName));
                        if (point != null)
                        {
                            Point.Points = int.Parse(point.Value);
                        }

                        Context.Current.Account.LastUpdated = DateTime.Now; 

                        if (Completed != null)
                        {
                            Completed(this, EventArgs.Empty);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, ex));
                    }
                }
            });
        }

        public int Delay { get { return 50; } }

        public bool IsUnique { get { return true; } }

        public event EventHandler Completed;

        public event EventHandler Started;

        public event EventHandler<FailedEventArgs> Failed;
    }
}
